package org.example.shop.service;

import org.example.shop.dao.GoodsDao;
import org.example.shop.dao.OrderDao;
import org.example.shop.pojo.Goods;
import org.example.shop.pojo.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private OrderDao orderDao;

    @Transactional
    @Override
    public Order createOrder(Long goodsId, Long buyCount) {
        Optional<Goods> goods = goodsDao.findById(goodsId);
        if (!goods.isPresent()) {
            throw new RuntimeException("商品不存在");
        }
        Goods g = goods.get();
        if (g.getStock() < buyCount) {
            throw new RuntimeException("商品库存不足");
        }
        Order o = new Order();
        o.setGid(goodsId).setPrice(g.getPrice() * buyCount).setCount(buyCount); // 设置购买数量
        o.setStatus(1); // 未支付
        o.setTitle(g.getName());
        orderDao.save(o); // 保存订单
        if (o == null || o.getId() < 1) {
            throw new RuntimeException("创建订单失败");
        }
        g.setStock(
                g.getStock() - buyCount
        ); // 业务上进行减
        goodsDao.save(g);// 保存新的库存
        return o;
    }

    @Override
    public Order query(Long id) {
        Optional<Order> optional = orderDao.findById(id);
        return optional.isPresent() ? optional.get() : null;
    }
}
